using UnityEngine;
using System.Collections;

public class Enemy : MonoBehaviour {

    [SerializeField] private Transform player;
    [SerializeField] private float attackDistance = 7f;
    [SerializeField] private GameObject floatingTextPrefab;

    [Header("Health")]
    [SerializeField] private int maxHealth = 2;

    [Header("Shooting")]
    [SerializeField] private Transform firePoint;
    [SerializeField] private float distance = 7f;
    [SerializeField] private LayerMask targetLayer;
    [SerializeField] private float startTime = 1f;
    private float timeBetweenShoots;
    private LineRenderer lr;
    private Animator animator;

    void Start()
    {
        timeBetweenShoots = startTime;
        lr = this.GetComponent<LineRenderer>();
        lr.enabled = false;
        animator = this.GetComponent<Animator>();
        player = GameObject.FindGameObjectWithTag("Player").transform;
    }


    void Update()
    {
        if (GameManager.instance.isGameActive == false) {
            return;
        }

        if (maxHealth <= 0) {
            Die();
            return;
        }

        if (Vector2.Distance(transform.position, player.position) <= attackDistance){
            if (timeBetweenShoots <= 0f) {
                //StartCoroutine(Shoot());
                timeBetweenShoots = startTime;
            }
            else {
                timeBetweenShoots -= Time.deltaTime;
            }
        }
    }

    IEnumerator Shoot() {
        lr.enabled = true;
        lr.SetPosition(0, firePoint.position);
        RaycastHit2D hit = Physics2D.Raycast(firePoint.position, -firePoint.right, distance, targetLayer);
        if (hit) {
            lr.SetPosition(1, hit.point);
            if (hit.transform.GetComponent<Player>() != null) {
                hit.transform.GetComponent<Player>().PlayerTakeDamage(1);
            }
        }
        else {
            lr.SetPosition(1, firePoint.position + (-firePoint.right * distance));
        }
        yield return null;

        lr.enabled = false;
    }

    public void TakeDamage(int damage) {
        if (maxHealth <= 0) {
            return;
        }
        maxHealth -= damage;
        Instantiate(floatingTextPrefab, transform.position, Quaternion.identity);
    }

    void Die() {
        animator.SetTrigger("Death");
        BoxCollider2D boxCollider2D = this.GetComponent<BoxCollider2D>();
        boxCollider2D.enabled = false;
        Destroy(this.gameObject, 10f);
    }
}
